package com.itcanteen.medical.docker.service.impl;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.facebody.model.v20191230.CompareFaceRequest;
import com.aliyuncs.facebody.model.v20191230.CompareFaceResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.itcanteen.medical.common.constant.CommonStatus;
import com.itcanteen.medical.common.constant.Contstant;
import com.itcanteen.medical.common.vo.CommonResponse;
import com.itcanteen.medical.docker.entity.Doctor;
import com.itcanteen.medical.docker.entity.Patient;
import com.itcanteen.medical.docker.entity.PatientDoctor;
import com.itcanteen.medical.docker.mapper.DoctorMapper;
import com.itcanteen.medical.docker.mapper.PatientDoctorMapper;
import com.itcanteen.medical.docker.mapper.PatientMapper;
import com.itcanteen.medical.docker.service.DoctorService;
import com.itcanteen.medical.docker.util.OSSUploadUtils;
import com.itcanteen.medical.docker.util.RabbitMqConfig;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.nio.channels.Channel;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

/**
 * @author 段段
 * @PackageName: com.itcanteen.medical.Doctor.service.impl
 * @ClassName: DoctorServiceImpl
 * @Description:
 * @data: 2020/12/15 14:15
 **/
@Service
public class DoctorServiceImpl implements DoctorService {

    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private PatientDoctorMapper patientDoctorMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Value("${oss.utils.endpoint}")
    private String endpoint;

    @Value("${oss.utils.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.utils.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.utils.bucket}")
    private String bucket;

    private static final String ak_id = "LTAI4G31e8bVQc6rVeF9X6JJ";
    private static final String ak_secret = "7d7D7aWAMIaUFqRZpRUJdadmzZfxNL";

    //预约的患者,就会收到消息
    @Override
    public void sendMsgToPatient(String name) throws IOException, TimeoutException {
        Doctor doctor = findDoctor(name);
        Example example = new Example(PatientDoctor.class);
        example.createCriteria().andEqualTo("doctorId",doctor.getId());
        List<PatientDoctor> patientDoctors = patientDoctorMapper.selectByExample(example);
        //编辑发送的消息
        String message = "你好,我是"+name+"医生,先已经上班,请速来就诊!!";
        for (PatientDoctor patientDoctor : patientDoctors) {
            Patient patient = patientMapper.selectByPrimaryKey(patientDoctor.getPatientId());
            //医生将消息发送至rabbitMq
            rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE_TOPICS_INFORM,"inform.email",message);

            //通过rabbitMq提醒预约人,医生上班
            send_email(message);
        }
    }

    //接收消息
    @RabbitListener(queues = {RabbitMqConfig.QUEUE_INFORM_EMAIL})
    public static void send_email(String message){
        System.out.println("接收到的消息是----->"+message);
    }

    //修改当前医生上班状态
    @Override
    public void updateStatus(String name) {
        Doctor doctor = findDoctor(name);
        doctor.setStatus("1");
        doctorMapper.updateByPrimaryKey(doctor);
    }

    public Doctor findDoctor(String name){
        Example example = new Example(Doctor.class);
        example.createCriteria().andEqualTo("name",name);

        Doctor doctor = doctorMapper.selectByExample(example).get(0);
        return doctor;
    }

    @Override
    public List<Doctor> findList() {
        return doctorMapper.selectAll();
    }

    @Override
    public void uploadFile(Long id, MultipartFile multipartFile) throws IOException {
        //获取上传的文件名称，并结合存放路径，构建心的问价名称
        String filename = multipartFile.getOriginalFilename();
        System.out.println(filename);
        //获取文件后缀名
        String[] split = filename.split("\\.");
        //生成随机
        String uuid = UUID.randomUUID().toString();
        System.out.println(uuid);
        //拼接，形成最新名称
        String newFile = uuid + "." + split[1];
        //输出最新的文件名
        System.out.println(newFile);
        //调用工具类进行上传
        OSSUploadUtils.uploadFile(bucket, multipartFile.getInputStream(), newFile, endpoint, accessKeyId, accessKeySecret);
        //路径
        String url = endpoint.replaceFirst("http://", "http://" + bucket + ".") + "/" + newFile;

        doctorMapper.updateKey(id, url);
    }

    @Override
    public Boolean login(String username, MultipartFile file) throws IOException {
        Example example = new Example(Doctor.class);
        example.createCriteria().andEqualTo("name",username);
        example.createCriteria().andNotEqualTo("status",0);
        Doctor doctor = doctorMapper.selectByExample(example).get(0);
        if(doctor == null){
            new CommonResponse<>(CommonStatus.INVALID.getCode(), Contstant.ErrorMsg.Class_DATA_NULL);
        }
        String images1 = doctor.getInformation();
        String images2 = getUrl(file);
        boolean b = faceContrast(images1, images2);
        if (b){
            System.out.println("通过:超过95%");
            return true;
        }else{
            System.out.println("失败:低于95%");
            return false;
        }
    }

    private String getUrl(MultipartFile multipartFile) throws IOException {
        //获取上传的文件名称，并结合存放路径，构建心的问价名称
        String filename = multipartFile.getOriginalFilename();
        System.out.println(filename);
        //获取文件后缀名
        String[] split = filename.split("\\.");
        //生成随机
        String uuid = UUID.randomUUID().toString();
        System.out.println(uuid);
        //拼接，形成最新名称
        String newFile = uuid + "." + split[1];
        //输出最新的文件名
        System.out.println(newFile);
        //调用工具类进行上传
        OSSUploadUtils.uploadFile(bucket, multipartFile.getInputStream(), newFile, endpoint, accessKeyId, accessKeySecret);
        //路径
        String url = endpoint.replaceFirst("http://", "http://" + bucket + ".") + "/" + newFile;

        return url;
    }

    private boolean faceContrast(String images1,String images2){
        boolean flag = false;

        //目前区域只开通了华东2(上海)
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", ak_id, ak_secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CompareFaceRequest request = new CompareFaceRequest();
        request.setRegionId("cn-shanghai");
        request.setImageURLA(images1);
        request.setImageURLB(images2);
        try {
            CompareFaceResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
            Float confidence = response.getData().getConfidence();
            System.out.println(confidence);
            if (confidence > 95){
                flag = true;
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("人脸对比ErrCode:" + e.getErrCode());
            System.out.println("人脸对比ErrMsg:" + e.getErrMsg());
            System.out.println("人脸对比RequestId:" + e.getRequestId());
        }
        return flag;
    }
}
